package xin.alum.aim.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.JavaType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import xin.alum.aim.AIM;
import xin.alum.aim.groups.ClusterMessage;
import xin.alum.aim.groups.SessionGroups;
import xin.alum.aim.groups.Sessions;
import xin.alum.aim.model.Pusher;
import xin.alum.aim.model.Reply;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.model.proto.Packet;
import xin.alum.aim.util.ApplicationContextUtil;
import xin.alum.aim.util.JSONUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.MessageListener;
import xin.alum.aim.util.ProtoDeserializer;
import xin.alum.aim.util.ProtoSerializer;

/**
 * @auther Alum(alum @ live.cn)
 * @date 2021/8/17 20:01
 */
class ReplyMessageListener implements MessageListener {

    @Autowired
    SessionGroups groups;

    @Autowired
    Sessions sessions;

    @Override
    public void onMessage(org.springframework.data.redis.connection.Message redisMessage, byte[] bytes) {
        if (AIM.message != null) {
            AIM.message.onMessage(redisMessage.getBody());
        } else {
            Pusher pusher = JSONUtils.fromJson(redisMessage.getBody(), new TypeReference<Pusher<Reply>>() {
            });
            if (pusher.getRecipient() == null || pusher.getRecipient().isEmpty() || pusher.getRecipient() == Sessions.ALL_SESSIONS) {
                sessions.sends(pusher.getData());
            } else {
                groups.get(pusher.getRecipient()).sends(pusher.getData());
            }
        }
    }
}
